<template>
  <div class="playsong">
    <!-- 背景图片 -->
    <div class="bgc"></div>

    <!-- 返回、搜索部分 -->
    <div class="header" ref="uu">
      <backTitle></backTitle>
      <div class="van-ellipsis">{{this.$store.state.title}}</div>
    </div>

    <!-- 音量滑动条 -->
    <div class="shenying" v-show="gecishow">
      <div class="shengyin">
        <van-icon name="volume" />
      </div>
      <van-slider
        v-model="volumevalue"
        @change="clickvolume"
        active-color="white"
        inactive-color="#A8A8A8"
      />
    </div>

    <!-- 歌词 -->
    <div class="geci" v-show="gecishow" @click="gecishow=false">
      <span>{{err}}</span>
      <ul>
        <template v-for="(item, index) in timelyric">
          <li :id="item[0]">{{item[1]}}</li>
        </template>
      </ul>
    </div>

    <!-- 音乐转盘 -->
    <div class="musiccircle" v-show="!gecishow" @click="gecishow=true">
      <div class="circle">
        <img :src="this.$store.state.img" />
      </div>
    </div>

    <div class="footer">
      <!-- 添加、评论 -->
      <div class="footer-gongneng" v-show="!gecishow">
        <span class="tianjia" @click="clicklove">
          <van-icon name="like-o" v-if="love" />
          <van-icon name="like" color="red" v-else />
        </span>
        <router-link :to="{path:'/pinglun/pinglun/id',query:{id:this.$store.state.id}}">
          <span class="pinglun">
            <van-icon name="chat-o" />
          </span>
        </router-link>
        <span class="footer-dian" @click="clickpop">
          <van-icon name="ellipsis" />
        </span>
      </div>

      <!-- 进度条 -->
      <div class="progress">
        <span>0.00</span>
        <van-progress :percentage="this.percent" pivot-text color="white" track-color="#A8A8A8" />
        <span>{{this.$store.state.playtime}}</span>
      </div>

      <!-- 播放按钮 -->
      <div class="bofang">
        <span @click="upsong">
          <i class="iconfont icon-leftarrow"></i>
        </span>
        <span class="pause" @click="play" v-if="!this.$store.state.showaudio">
          <van-icon name="pause-circle-o" />
        </span>
        <span class="pause" @click="play" v-if="this.$store.state.showaudio">
          <van-icon name="play-circle-o" />
        </span>
        <span class="nextsong" @click="downsong">
          <i class="iconfont icon-leftarrow"></i>
        </span>
      </div>
    </div>

    <!-- 歌曲详情弹出层 -->
    <van-popup v-model="songdetailshow" class="songdetail" :style="{ height: '43%' }" round>
      <div class="detail">
        <span class="singerimg">
          <img :src="singerimg" />
        </span>
        <div class="name">
          <div class="van-ellipsis songname">{{name}}</div>
          <div class="van-ellipsis singername">{{singername}}</div>
        </div>
      </div>
      <!-- 添加 -->
      <div class="add" @click="clickplaylistpop()">
        <van-icon name="add-o" />
        <span>添加到歌单</span>
      </div>
      <!-- 歌手 -->
      <router-link
        :to="{path:'/geshou/singerdetail/id',
              query:{id:singerid,title:singername}}"
      >
        <div class="singer">
          <van-icon name="manager-o" />
          <span>歌手：{{singername}}</span>
        </div>
      </router-link>
      <!-- 评论 -->
      <router-link :to="{path:'/pinglun/pinglun/id',query:{id:songid}}">
        <div class="comment">
          <van-icon name="chat-o" />
          <span>评论</span>
        </div>
      </router-link>
    </van-popup>

    <!-- 歌单弹出层 -->
    <van-popup v-model="playlistshow" :style="{height: '50%' }" round class="playlistpop">
      <div class="playlist-title">我的歌单</div>

      <div class="usersonglists">
        <template v-for="(item, index) in playlist">
          <div class="usersonglist" @click="addsong(item.id)">
            <span>
              <img :src="item.coverImgUrl" />
            </span>
            <div class="van-ellipsis">{{item.name}}</div>
          </div>
        </template>
      </div>
    </van-popup>
  </div>
</template>

<script>
import backTitle from "../../components/back";
import send from "../../navshow";

export default {
  data() {
    return {
      songlist: [], //歌手单曲
      singer: [], //歌手详情
      title: "", //歌名
      img:
        "http://img0.imgtn.bdimg.com/it/u=1578705784,2343604028&fm=26&gp=0.jpg", //转盘
      src: [], //播放地址
      gecishow: false, //隐藏歌词
      love: true, //是否添加
      lyric: [], //获取歌词
      times: [], //时间数组
      timelyric: [], //时间与歌词
      isshengyin: true, //是否静音
      curtime: "0", //当前的播放时间
      songlength: "", //获取歌曲的长度
      percent: 0, //进度条百分比
      err: "", //报错时
      count: "0", //定时器
      offsetTop: "", //.active标签距离屏幕的高
      volumevalue: 50, //音量键大小
      songdetailshow: false, //歌曲详情弹出层
      songid: "", //歌曲id
      singerid: "", //歌手id
      singerimg: "", //歌手头像
      name: "", //歌名
      singername: "", //歌手名
      playlistshow: false, //歌单弹出层
      playlist: [] //用户歌单
    };
  },
  created() {
    // 隐藏导航栏
    send.$emit("tab-show", false);

    // 隐藏播放器
    this.$store.commit("showplayer", false);

    var id = this.$route.query.id; //获取歌曲id
    var lrc = "http://localhost:3000/lyric?id=" + id; //获取歌词
    var songld = "http://localhost:3000/song/detail?ids=" + id; //获取歌曲详情

    // 获取歌词
    if (id != null) {
      this.axios
        .get(lrc)
        .then(res => {
          // var arr = [];
          var twoarr = []; //用于存放一个二维数组
          // arr = res.data.lrc.lyric.replace(/\[.*?\]/g, "");
          // this.lyric = arr.split("\n");
          var lyric = res.data.lrc.lyric.split("[").slice(1); //.slice() 删除数组第一个元素
          lyric.forEach((element, i) => {
            var t = element.split("]");
            var lrcline = t[1]; //每行歌词
            var tt = t[0].split(".");
            var ttt = tt[0].split(":");
            var miao = ttt[0] * 60 + ttt[1] * 1; //每行时间
            twoarr.push([miao, lrcline]); //将歌词时间与歌词存放在一个二维数组中
            this.timelyric = twoarr;
          });
        })
        .catch(err => {
          this.err = "当前暂无歌词";
        });
    }

    var date = new Date();

    // 获取喜欢音乐列表
    this.axios({
      url:
        "http://localhost:3000/likelist?" +
        sessionStorage.getItem("id") +
        "&timestamp=" +
        date.getTime(),
      withCredentials: true //关键
    }).then(res => {
      let ids = res.data.ids;
      ids.forEach(element => {
        if (element == this.$route.query.id) {
          this.love = false;
        }
      });
    });
  },
  components: {
    // 注册一个局部组件
    backTitle
  },
  methods: {
    // 调节音量大小
    clickvolume(val) {
      var auto = document.querySelector("#music"); //获取audio对象
      auto.volume = val * 0.01;
    },

    // 点击播放
    play() {
      var auto = document.querySelector("#music");
      if (this.$store.state.showaudio && this.$store.state.id != null) {
        auto.play();
        this.$store.commit("showAudio", false);
      } else {
        auto.pause();
        this.$store.commit("showAudio", true);
        if (this.$store.state.id == null) {
          this.$toast("请选择歌曲");
        }
      }
    },

    // 点击添加歌曲
    clicklove() {
      var love = document.querySelector(".tianjia");
      this.love = !this.love;

      // 更改时间戳
      var date = new Date();
      this.$store.commit("changetimestamp", date.getTime());

      // 喜欢
      if (this.love == false) {
        let url = "http://localhost:3000/like?id=" + this.$store.state.id;
        this.axios({
          url,
          withCredentials: true //关键
        }).then(res => {
          if ((res.status = 200)) {
            this.$toast('收藏成功')
          }
        });
      } else {
        // 不喜欢
        let url ="http://localhost:3000/like?like=false&id=" + this.$store.state.id;
        this.axios({
          url,
          withCredentials: true //关键
        }).then(res => {
          this.$toast('取消收藏')
        });
      }
    },

    // 点击静音
    clickshengyin() {
      var auto = document.querySelector("#music");

      this.isshengyin = !this.isshengyin;
      if (!this.isshengyin) {
        auto.muted = true;
      } else {
        auto.muted = false;
      }
    },

    // 点击上一首
    upsong() {
      $(".geci").scrollTop(0);
      var songlist = this.$store.state.songlist; //获取歌单
      var index = this.$store.state.index; //获取索引值
      this.$store.commit("showAudio", false); //隐藏播放器
      if (index > 0 && this.$store.state.id != null) {
        index--;
        this.$store.commit("changeindex", index);
        this.$store.commit("changeid", songlist[index].id);
        var url = "http://localhost:3000/song/url?id=" + this.$store.state.id;
        var lrc = "http://localhost:3000/lyric?id=" + this.$store.state.id;

        //更改播放地址
        this.axios.get(url).then(res => {
          if (res.status == 200) {
            this.$store.commit("changesrc", res.data.data[0].url);
          } else {
            this.$toast("当前歌曲暂时不能播放");
          }
        });

        // 获取歌词
        this.axios
          .get(lrc)
          .then(res => {
            // var arr = [];
            var twoarr = []; //用于存放一个二维数组
            // arr = res.data.lrc.lyric.replace(/\[.*?\]/g, "");
            // this.lyric = arr.split("\n");
            var lyric = res.data.lrc.lyric.split("[").slice(1);
            lyric.forEach((element, i) => {
              var t = element.split("]");
              var lrcline = t[1]; //每行歌词
              var tt = t[0].split(".");
              var ttt = tt[0].split(":");
              var miao = ttt[0] * 60 + ttt[1] * 1; //每行时间
              twoarr.push([miao, lrcline]); //将歌词时间与歌词存放在一个二维数组中
              this.timelyric = twoarr;
            });
            this.err = "";
          })
          .catch(err => {
            this.err = "当前暂无歌词";
          });

        this.percent = 0;
      } else {
        this.$store.commit("showAudio", true);
      }
    },

    // 点击下一首
    downsong() {
      $(".geci").scrollTop(0);
      var songlist = this.$store.state.songlist; //获取歌单
      var index = this.$store.state.index; //获取索引值
      this.$store.commit("showAudio", false);
      index++;
      if (index < songlist.length && this.$store.state.id != null) {
        this.$store.commit("changeindex", index);
        this.$store.commit("changeid", songlist[index].id);
        var url = "http://localhost:3000/song/url?id=" + this.$store.state.id;
        var lrc = "http://localhost:3000/lyric?id=" + this.$store.state.id;

        //更改播放地址
        this.axios.get(url).then(res => {
          if (res.status == 200) {
            this.$store.commit("changesrc", res.data.data[0].url);
          } else {
            this.$toast("当前歌曲暂时不能播放");
          }
        });

        // 获取歌词
        this.axios
          .get(lrc)
          .then(res => {
            var twoarr = []; //用于存放一个二维数组
            var lyric = res.data.lrc.lyric.split("[").slice(1);
            lyric.forEach((element, i) => {
              var t = element.split("]");
              var lrcline = t[1]; //每行歌词
              var tt = t[0].split(".");
              var ttt = tt[0].split(":");
              var miao = ttt[0] * 60 + ttt[1] * 1; //每行时间
              twoarr.push([miao, lrcline]); //将歌词时间与歌词存放在一个二维数组中
              this.timelyric = twoarr;
            });
            this.err = "";
          })
          .catch(err => {
            this.err = "当前暂无歌词";
          });

        this.percent = 0;
      } else {
        this.$toast("已经到底啦");
        this.$store.commit("showAudio", true);
      }
    },

    // 显示歌曲详情弹出层
    clickpop(id, name, singername) {
      this.songid = this.$route.query.id;
      this.songdetailshow = true;

      let url = "http://localhost:3000/song/detail?ids=" + this.songid;
      this.axios.get(url).then(res => {
        console.log(res.data.songs[0].ar[0]);
        this.singerid = res.data.songs[0].ar[0].id;
        this.singerimg = res.data.songs[0].al.picUrl; //歌手头像
        this.name = res.data.songs[0].al.name;
        this.singername = res.data.songs[0].ar[0].name;
      });
    },

    // 显示歌单弹出层
    clickplaylistpop() {
      this.songdetailshow = false;
      this.playlistshow = true;
      let url =
        "http://localhost:3000/user/playlist?uid=" +
        sessionStorage.getItem("id");

      // 获取用户歌单
      this.axios({
        url,
        withCredentials: true //关键
      }).then(res => {
        if (res.status == 200) {
          this.playlist = res.data.playlist;
        }
      });
    },

    // 添加歌曲
    addsong(id) {
      let url =
        "http://localhost:3000/playlist/tracks?op=add&pid=" +
        id +
        "&tracks=" +
        this.songid;

      // 添加歌单
      this.axios({
        url,
        withCredentials: true //关键
      }).then(res => {
        if (res.status == 200) {
          this.playlistshow = false;
          this.$toast("添加成功");
        }
      });
    }
  },
  // 挂载时
  mounted() {
    // console.log(this.$refs.uu);

    // 头像旋转
    var angle = 0;
    const timeimg = setInterval(() => {
      angle += 2;
      $(".circle").css("transform", "rotate(" + angle + "deg)");
    }, 100);
    // 通过$once来监听定时器，在beforeDestroy钩子可以被清除
    this.$once("hook:beforeDestroy", () => {
      clearInterval(timeimg);
    });

    // 获取当前的播放时长
    var auto = document.querySelector("#music");

    var audiotime = Math.ceil(auto.currentTime);
    this.percent = audiotime;
    var currenttime = Math.ceil(this.$store.state.playtime * 60);
    // 进度条的速度
    var timepercent = window.setInterval(() => {
      if (this.percent >= 0 && this.percent < 100 && auto.ended == false) {
        this.percent++;
      } else if(auto.ended==true && this.percent >= 99){
        clearInterval(timepercent);
        this.downsong();
        $(".geci li").removeClass("active");
        this.percent = 0;
      }
    }, currenttime * 10);

    // 音频播放位置改变时
    auto.ontimeupdate = function() {};
  },
  computed: {
    // 返回当前进度条的进度
    watchpercent() {
      return this.percent;
    },
    // 监听音乐id的变化
    watchid() {
      return this.$store.state.id;
    },
    // 监听当前播放时间的变化
    watchcurtime() {
      return this.curtime;
    },
    // 监听active距离屏幕的高
    watchoffsetTop() {
      return this.offsetTop;
    },
    // 监听时间戳的变化
    watchtimestamp() {
      return this.$store.state.timestamp;
    }
  },
  watch: {
    // 监听当前播放进度
    watchpercent(val) {
      var auto = document.querySelector("#music");
      var audiotime = Math.ceil(auto.currentTime);
      this.curtime = auto.currentTime; //获取当前的播放时间
      var songlength = Math.ceil(this.$store.state.playtime * 60);
      this.percent = (audiotime / songlength) * 100; //当前的播放进度

      // 获取歌曲播放长度
      var auto = document.querySelector("#music");
      var songLength = auto.duration;
      var songlength = (songLength / 60).toFixed(2);
      if (songlength == "NaN") {
        songlength = "4.30";
      }
      this.$store.commit("playTime", songlength);
    },

    // 监听id的变化
    watchid: function(id) {
      var lrc = "http://localhost:3000/lyric?id=" + id; //获取歌词
      $(".geci").scrollTop(0);

      // 获取歌词
      if (id != null) {
        this.axios
          .get(lrc)
          .then(res => {
            var twoarr = []; //用于存放一个二维数组
            var lyric = res.data.lrc.lyric.split("[").slice(1); //.slice() 删除数组第一个元素
            lyric.forEach((element, i) => {
              var t = element.split("]");
              var lrcline = t[1]; //每行歌词
              var tt = t[0].split(".");
              var ttt = tt[0].split(":");
              var miao = ttt[0] * 60 + ttt[1] * 1; //每行时间
              twoarr.push([miao, lrcline]); //将歌词时间与歌词存放在一个二维数组中
              this.timelyric = twoarr;
            });
          })
          .catch(err => {
            this.err = "当前暂无歌词";
          });

        // 判断是否已经是喜欢的音乐
        this.axios({
          url:
            "http://localhost:3000/likelist?" +
            sessionStorage.getItem("id") +
            "&timestamp=" +
            id,
          withCredentials: true //关键
        }).then(res => {
          let ids = res.data.ids;
          for (let i = 0; i < ids.length; i++) {
            if (ids[i] == id) {
              this.love = false;
              break;
              console.log("喜欢");
            } else {
              this.love = true;
            }
          }
        });
      }
    },

    // 监听当前播放时间的变化
    watchcurtime(val) {
      var $this = this;
      // 歌词同步
      $(".geci li").each(function() {
        if (
          $(this).attr("id") <= val &&
          val <=
            $(this)
              .next()
              .attr("id") &&
          $(this).text() != ""
        ) {
          $(this)
            .addClass("active")
            .siblings()
            .removeClass("active");
          $this.offsetTop = $(".active").offset().top; //获取active标签的距离屏幕的高
        }
      });
    },

    // 监听active距离屏幕的高
    watchoffsetTop(val) {
      var scrollTop = $(".geci").scrollTop();
      if (val > 281 && val <= 482) {
        $(".geci").scrollTop(scrollTop + 35);
      } else if (val > 482) {
        $(".geci").scrollTop(val - 245);
      } else if (val < 123) {
        $(".geci").scrollTop(scrollTop - 245);
      }
    }
  }
};
</script>   

<style>
/* 背景 */
.playsong {
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  position: relative;
}

.playsong .bgc {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  background: url("https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1108963040,2877248972&fm=26&gp=0.jpg");
  background-size: cover;
  z-index: -1;
  /* 毛玻璃效果 */
  filter: blur(3px);
}

/* 返回、搜索部分 */
.playsong .header {
  display: flex;
  width: 100vw;
  height: 60px;
  align-items: center;
  color: white;
  position: fixed;
  top: 0;
  z-index: 666;
  border-bottom: 1px lightgray solid;
}

.playsong .header .back {
  margin-left: 15px;
  margin-right: 10px;
}

.van-ellipsis {
  width: 70vw;
  text-align: center;
  font-weight: lighter;
  font-size: 18px;
}

.header span {
  font-size: 16px;
  color: white;
}

.playsong .header .dian {
  transform: rotate(90deg);
}

.play {
  width: 300px;
  height: 60px;
  margin: auto;
}

/* 音量键 */
.shenying {
  width: 92vw;
  height: 5vh;
  margin: 5vh auto 5px;
}

.shenying .shengyin {
  position: relative;
  left: 0;
  top: 18px;
}

.shenying .shengyin i {
  font-size: 16px;
  color: #dbdbdb;
}

.shenying .van-slider {
  width: 85vw;
  margin-left: 7vw;
  top: 0;
}

.shenying .van-slider > div > div > div {
  width: 14px !important;
  height: 14px !important;
}

/* 歌词部分 */
.geci {
  width: 100vw;
  height: 400px;
  margin: 1vh auto 0;
  overflow: scroll;
  text-align: center;
}

.geci ul {
  width: 90vw;
  margin: 40px auto 0;
}

.geci li {
  width: 100%;
  height: 25px;
  text-align: center;
  font-size: 16px;
  overflow: hidden;
  margin-top: 10px;
  color: white;
}

.geci .active {
  color: #222831;
  font-weight: bold;
}

/* 音乐转盘部分 */
.playsong .musiccircle {
  width: 100vw;
  height: 460px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.playsong .musiccircle .circle {
  margin-top: 20px;
}

.playsong .musiccircle .circle img {
  width: 250px;
  height: 250px;
  border-radius: 50%;
}

/* 底部 */

/* 添加评论 */
.footer-gongneng {
  width: 100vw;
  height: 5vh;
  display: flex;
  justify-content: space-around;
  margin-bottom: 10px;
}

.footer-gongneng a {
  height: 100%;
}

.footer-gongneng .pinglun {
  margin-top: 5px;
}

.footer-gongneng i {
  font-size: 24px;
  color: white;
}

.footer-dian {
  transform: rotate(90deg);
}

/* 进度条 */
.progress {
  margin: 3vh 0 1vh 0;
  width: 95vw;
  margin: 0 auto;
  background: none;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.progress div {
  width: 80vw;
}

.progress > span {
  font-size: 12px;
  color: #dbdbdb;
}

/* 播放切换按钮 */
.bofang {
  width: 80vw;
  height: 50px;
  display: flex;
  justify-content: space-around;
  align-items: flex-start;
  margin: 0 auto 0.5vh;
}

.bofang i {
  font-size: 32px;
  color: #dbdbdb;
}

.pause i {
  font-size: 50px;
  font-weight: normal;
}

.nextsong {
  transform: rotate(180deg);
}

/* 功能 */
.playsong .add,
.playsong .singer,
.playsong .comment {
  width: 75vw;
  height: 8vh;
  margin: 0 auto 0;
  border-bottom: 1px solid #dbdbdd;
  display: flex;
  align-items: center;
}

.playsong .add i,
.playsong .singer i,
.playsong .comment i {
  font-size: 18px;
  margin-left: 1px;
  color: #333333;
}

.playsong .add span,
.playsong .singer span,
.playsong .comment span {
  width: 80vw;
  margin-left: 5vw;
  font-size: 16px;
}
</style>